﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Resources;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Converter;
using csla4Skeleton.UI.SL.Resources.Utility;
using csla4Skeleton.UI.SL.NghiepVu.MuaSanPham.DM_LoaiHoaDon;
using csla4Skeleton.UI.SL.DanhMuc.DM_Kho;
using csla4Skeleton.UI.SL.DanhMuc.DM_HangHoa;
using csla4Skeleton.UI.SL.DanhMuc.DM_TaiKhoan;
using csla4Skeleton.UI.SL.DanhMuc.DM_DonViTinh;
using csla4Skeleton.UI.SL.DanhMuc.DM_ThueSuat;
using csla4Skeleton.UI.SL.DanhMuc.DM_TinhChatHangHoa;
using csla4Skeleton.UI.SL.NghiepVu.MuaSanPham.DM_LoaiMuaSanPham;
using csla4Skeleton.UI.SL.NghiepVu.TaiSanCoDinh.DM_DoiTuongTHCP;
using csla4Skeleton.UI.SL.NghiepVu.BanSanPham.BSP_BanHangHoa;
using csla4Skeleton.UI.SL.HeThong.HT_ThongTinCongTy;
using csla4Skeleton.UI.SL.DanhMuc.DM_NhaCungCap;
using csla4Skeleton.UI.SL.NghiepVu.Kho.K_ListNhapKho;
using csla4Skeleton.UI.SL.NghiepVu.Kho.K_ListXuatKho;
using csla4Skeleton.UI.SL.NghiepVu.Kho.K_TonKho;
using Accounting.Library;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using System.ComponentModel;
using Utility;
using Accounting.Library.Utility;
using System.Windows.Media;

namespace csla4Skeleton.UI.SL.NghiepVu.Kho.K_PhieuXuatKho
{
    public partial class K_PhieuXuatKho_MainWindow : UserControl, Csla.Xaml.ISupportNavigation
    {
        #region ISupportNavigation Members
        public bool CreateBookmarkAfterLoadCompleted
        {
            get { return true; }
        }

        public event EventHandler LoadCompleted;

        protected virtual void OnLoadCompleted()
        {
            MessageBox.Show("Load complete");
            if (LoadCompleted != null)
                LoadCompleted(this, EventArgs.Empty);
        }

        /// <summary>
        /// Set parameters for user control
        /// </summary>
        /// <param name="parameters">[Khoa];[Ma Chung Tu Phat Sinh]</param>
        public void SetParameters(string parameters)
        {
            try
            {
                if (parameters == "")
                {
                    Khoa = null;
                    MaChungTuPhatSinh = "";
                }
                else
                {
                    Khoa = Int32.Parse(parameters.Split(';')[0]);
                    MaChungTuPhatSinh = parameters.Split(';')[1];
                }
            }
            catch
            {
                Khoa = null;
                MaChungTuPhatSinh = "";
            }
        }

        public string Title
        {
            get { return "PhieuXuatKho"; }
        }
        #endregion

        #region Load Methods
        private System.Nullable<int> Khoa = null;
        private string MaChungTuPhatSinh = "";

        public K_PhieuXuatKho_MainWindow(int Khoa)
        {
            this.Khoa = Khoa;
        }

        public K_PhieuXuatKho_MainWindow()
        {
            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.Kho.K_PhieuXuatKho.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);

            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
                System.Windows.Data.CollectionViewSource K_PhieuXuatKho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_PhieuXuatKho_ViewModelSource"];
                K_PhieuXuatKho_ViewModel K_PhieuXuatKho_ViewMode;
                if (Khoa == null)
                {
                    K_PhieuXuatKho_ViewMode = new K_PhieuXuatKho_ViewModel();
                }
                else
                {
                    K_PhieuXuatKho_ViewMode = new K_PhieuXuatKho_ViewModel((int)Khoa);
                }

                K_PhieuXuatKho_ViewMode.LoadCompleted += new EventHandler(K_PhieuXuatKho_ViewModel_LoadCompleted);
                K_PhieuXuatKho_ViewMode.ChildList_AddedNew += new K_PhieuXuatKho_ViewModel.ChildList_AddedNew_EventHandler(K_PhieuXuatKho_ViewModel_ChildList_AddedNew);

                K_PhieuXuatKho_ViewMode.hangHoaIdChanged += new K_PhieuXuatKho_ViewModel.HangHoaIdChanged_EventHandler(K_PhieuXuatKho_HangHoaIdChanged);
                K_PhieuXuatKho_CollectionViewSource.Source = new List<object> { K_PhieuXuatKho_ViewMode };

                System.Windows.Data.CollectionViewSource dm_NhaCungCap_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_NhaCungCap_ListViewModelSource"];
                DM_NhaCungCap_ListViewModel dm_NhaCungCap_ListViewModel = new DM_NhaCungCap_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode, BusinessConfiguration.Configuration.DieuKienLocNCC_KhachHang);
                dm_NhaCungCap_CollectionViewSource.Source = new List<object> { dm_NhaCungCap_ListViewModel };

                System.Windows.Data.CollectionViewSource dm_HangHoa_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_HangHoa_ListViewModelSource"];
                DM_HangHoa_ListViewModel dm_HangHoa_ListViewModel = new DM_HangHoa_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                dm_HangHoa_CollectionViewSource.Source = new List<object> { dm_HangHoa_ListViewModel };

                System.Windows.Data.CollectionViewSource ht_ThongTinCongTy_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["HT_ThongTinCongTy_ListViewModelSource"];
                HT_ThongTinCongTy_ListViewModel ht_ThongTinCongTy_ListViewModel = new HT_ThongTinCongTy_ListViewModel(BusinessConfiguration.Configuration.GridViewFetchMode);
                ht_ThongTinCongTy_CollectionViewSource.Source = new List<object> { ht_ThongTinCongTy_ListViewModel };

                System.Windows.Data.CollectionViewSource dm_DonViTinh_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_DonViTinh_ListViewModelSource"];
                DM_DonViTinh_ListViewModel dm_DonViTinh_ListViewModel = new DM_DonViTinh_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                dm_DonViTinh_CollectionViewSource.Source = new List<object> { dm_DonViTinh_ListViewModel };

                System.Windows.Data.CollectionViewSource dm_DoiTuongTHCP_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_DoiTuongTHCP_ListViewModelSource"];
                DM_DoiTuongTHCP_ListViewModel dm_DoiTuongTHCP_ListViewModel = new DM_DoiTuongTHCP_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                dm_DoiTuongTHCP_CollectionViewSource.Source = new List<object> { dm_DoiTuongTHCP_ListViewModel };

                System.Windows.Data.CollectionViewSource dm_Kho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_Kho_ListViewModelSource"];
                DM_Kho_ListViewModel dm_Kho_ListViewModel = new DM_Kho_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                dm_Kho_CollectionViewSource.Source = new List<object> { dm_Kho_ListViewModel };
            }
        }
        #endregion

        #region Event Handle
        private void LayoutRoot_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                K_PhieuXuatKho_ViewModel vm = GetViewModel();
                if (e.Key == Key.S)
                {
                    if (vm.CanSave && CheckBeforeSave())
                    {
                        vm.Save(sender, new Csla.Xaml.ExecuteEventArgs());
                    }
                }
                else if (e.Key == Key.F6)
                {
                    AddItems();
                }
                else if (e.Key == Key.D1)
                {
                    this.K_PhieuXuatKho_PhieuXuatKhoChiTietTab.IsSelected = true;
                }
            }
            e.Handled = true;
        }

        void AddItemButton_Click(object sender, RoutedEventArgs e)
        {
            AddItems();
        }

        void DeleteItemButton_Click(object sender, RoutedEventArgs e)
        {
            DeleteItems();
        }

        public void AddItems()
        {
            if (this.K_PhieuXuatKho_PhieuXuatKhoChiTietTab.IsSelected)
            {
                AddPhieuXuatKhoDetailsItem();
            }
        }

        void DeleteItems()
        {
            if (this.K_PhieuXuatKho_PhieuXuatKhoChiTietTab.IsSelected)
            {
                K_PhieuXuatKho_ChiTietChild ChiTietChild = (K_PhieuXuatKho_ChiTietChild)(this.K_PhieuXuatKho_PhieuXuatKhoChiTietGridView.SelectedItem);
                IList<K_PhieuXuatKho_ChiTietChild> list = GetViewModel().Model.K_PhieuXuatKho_ChiTiets;
                int index = list.IndexOf(ChiTietChild);
                DeletePhieuXuatKhoDetailsItem(index);
            }
        }

        void GridView_AddingNewDataItem(object sender, GridViewAddingNewEventArgs e)
        {
            var grid = e.OwnerGridViewItemsControl;
            if (grid.Items.Count > 0)
            {
                GridViewUtil.FocusRow((RadGridView)grid, grid.Items.Count - 1);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    grid.CurrentCellInfo = new GridViewCellInfo(grid.Items[grid.Items.Count - 1], grid.Columns[0]);
                    grid.Focus();
                    grid.BeginEdit();
                }));
            }
        }

        private void SaveAndNewButton_Click(object sender, RoutedEventArgs e)
        {
            if (CheckBeforeSave())
                this.GetViewModel().SaveAndNew();
        }

        private void K_PhieuXuatKho_GeneralInformation_NhaCungCapId_AddItemButton_Click(object sender, RoutedEventArgs e)
        {
            DM_NhaCungCap_ChildWindow dm_NhaCungCap_ChildWindow = new DM_NhaCungCap_ChildWindow();
            dm_NhaCungCap_ChildWindow.Show();
            dm_NhaCungCap_ChildWindow.SaveClicked += new EventHandler(dm_NhaCungCap_ViewModel_Saved);
        }
        #endregion

        #region View Model Related Methods
        private K_PhieuXuatKho_ViewModel GetViewModel()
        {
            System.Windows.Data.CollectionViewSource K_PhieuXuatKho_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["K_PhieuXuatKho_ViewModelSource"];
            return ((List<object>)K_PhieuXuatKho_CollectionViewSource.Source)[0] as K_PhieuXuatKho_ViewModel;
        }

        private void K_PhieuXuatKho_ViewModel_ChildList_AddedNew(object sender, ChildListAddedNewArgs e)
        {
            this.K_PhieuXuatKho_PhieuXuatKhoChiTietGridView.OnAddingNewDataItem(new GridViewAddingNewEventArgs(this.K_PhieuXuatKho_PhieuXuatKhoChiTietGridView));
        }

        private void K_PhieuXuatKho_ViewModel_LoadCompleted(object sender, EventArgs e)
        {
            if (MaChungTuPhatSinh != "")
            {
                GetViewModel().Model.ErrorMessage = "Đã phát sinh chứng từ " + MaChungTuPhatSinh + ". Không được phép chỉnh sửa.";
                SetEnableForUserControls(ContentRoot);
            }
        }

        private void SetEnableForUserControls(DependencyObject root)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(root, i);
                if (child is Control)
                {
                    Control control = child as Control;
                    if (control == this.GoBackToParentListButton)
                    {
                        control.IsEnabled = true;
                    }
                    else
                    {
                        control.IsEnabled = false;
                    }
                }
                else
                {
                    SetEnableForUserControls(child);
                }
            }
        }

        void dm_NhaCungCap_ViewModel_Saved(object sender, EventArgs e)
        {
            System.Windows.Data.CollectionViewSource dm_NhaCungCap_ListViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_NhaCungCap_ListViewModelSource"];
            DM_NhaCungCap_ListViewModel vm = ((List<object>)dm_NhaCungCap_ListViewSource.Source)[0] as DM_NhaCungCap_ListViewModel;
            vm.GetDM_NhaCungCap_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode, BusinessConfiguration.Configuration.DieuKienLocNCC_KhachHang);
        }

        public void K_PhieuXuatKho_HangHoaIdChanged(object sender, HangHoaIdChangedEventArgs e)
        {
            K_PhieuXuatKho_ChiTietChild ChiTietChild = GetViewModel().Model.K_PhieuXuatKho_ChiTiets[e.Index];
            System.Windows.Data.CollectionViewSource dm_HangHoa_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_HangHoa_ListViewModelSource"];
            DM_HangHoa_ListViewModel dm_HangHoa_ListViewModel = ((List<object>)dm_HangHoa_CollectionViewSource.Source)[0] as DM_HangHoa_ListViewModel;
            System.Collections.Generic.IList<DM_HangHoaInfo> list = dm_HangHoa_ListViewModel.Model.getListOfInfo();

            foreach (DM_HangHoaInfo item in list)
            {
                if (item.Khoa == e.HangHoaId)
                {
                    ChiTietChild.DienGiai = item.TenViet;
                    ChiTietChild.DonGia = (double)item.DonGiaBan;
                    ChiTietChild.KhoId = (int)item.KhoNgamDinhId;
                    ChiTietChild.DVTId = item.DonViTinhId;
                    break;
                }
            }
        }

        private void AddPhieuXuatKhoDetailsItem()
        {
            GetViewModel().AddK_PhieuXuatKho_ChiTietItem();
        }

        private void DeletePhieuXuatKhoDetailsItem(int Index)
        {
            GetViewModel().DeleteK_PhieuXuatKho_ChiTietItem(Index);
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.GetViewModel().CanSave && CheckBeforeSave())
            {
                this.GetViewModel().SavePhieuXuatKho();
            }
        }

        /// <summary>
        /// Kiem tra han muc ky gui & han muc cong no
        /// </summary>
        /// <returns></returns>
        private bool CheckBeforeSave()
        {
            bool result = true;

            if ((bool)this.K_PhieuXuatKho_MoreInformation_LyDoXuatKho_BanHang_RadioButton.IsChecked &&
                (bool)this.K_PhieuXuatKho_MoreInformation_PhuongThucThanhToan_ThanhToanCongNo_RadioButton.IsChecked)
            {
                int? hanNo =
                    ((DM_NhaCungCapInfo)K_PhieuXuatKho_GeneralInformation_NhaCungCapId_ComboBox.SelectedItem).HanNo;
                hanNo = hanNo == null ? 0 : hanNo;

                double? dinhMucCongNo =
                    ((DM_NhaCungCapInfo)K_PhieuXuatKho_GeneralInformation_NhaCungCapId_ComboBox.SelectedItem).DinhMucCongNo;
                dinhMucCongNo = dinhMucCongNo == null ? 0 : dinhMucCongNo;

                double? dinhMucCongNoDaDung =
                    ((DM_NhaCungCapInfo)K_PhieuXuatKho_GeneralInformation_NhaCungCapId_ComboBox.SelectedItem).DinhMucCongNoDaDung;
                dinhMucCongNoDaDung = dinhMucCongNoDaDung == null ? 0 : dinhMucCongNoDaDung;

                dinhMucCongNoDaDung = dinhMucCongNoDaDung + (double)GetViewModel().Model.TongTien;

                if (dinhMucCongNoDaDung > dinhMucCongNo)
                {
                    if (MessageBox.Show
                        ("Định mức công nợ đã dùng vượt quá hạn mức công nợ. Bạn có muốn tiếp tục?", "Hệ thống thông tin kế toán", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
                    {
                        result = false;
                    }
                }
            }
            else if ((bool)this.K_PhieuXuatKho_MoreInformation_LyDoXuatKho_KyGui_RadioButton.IsChecked)
            {
                int? hanKyGui =
                    ((DM_NhaCungCapInfo)K_PhieuXuatKho_GeneralInformation_NhaCungCapId_ComboBox.SelectedItem).HanKyGui;
                hanKyGui = hanKyGui == null ? 0 : hanKyGui;

                double? dinhMucKyGui =
                    ((DM_NhaCungCapInfo)K_PhieuXuatKho_GeneralInformation_NhaCungCapId_ComboBox.SelectedItem).DinhMucKyGui;
                dinhMucKyGui = dinhMucKyGui == null ? 0 : dinhMucKyGui;

                double? dinhMucKyGuiDaDung =
                    ((DM_NhaCungCapInfo)K_PhieuXuatKho_GeneralInformation_NhaCungCapId_ComboBox.SelectedItem).DinhMucKyGuiDaDung;
                dinhMucKyGuiDaDung = dinhMucKyGuiDaDung == null ? 0 : dinhMucKyGuiDaDung;

                double tongTien = GetViewModel().Model.TongTien == null ? 0 : (double)GetViewModel().Model.TongTien;
                dinhMucKyGuiDaDung = dinhMucKyGuiDaDung + tongTien;
                if (dinhMucKyGuiDaDung > dinhMucKyGui)
                {
                    if (MessageBox.Show
                        ("Định mức ký gửi đã dùng vượt quá hạn mức ký gửi. Bạn có muốn tiếp tục?", "Hệ thống thông tin kế toán", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
                    {
                        result = false;
                    }
                }
            }

            return result;
        }
        #endregion
    }
}